import { createStore } from 'vuex'
import { getToken, getUserInfo, clearAuth } from '@/utils/auth'

export default createStore({
  state: {
    isLoggedIn: false,
    userInfo: null
  },
  getters: {
    isLoggedIn: state => state.isLoggedIn,
    userInfo: state => state.userInfo
  },
  mutations: {
    SET_LOGIN_STATE(state, isLoggedIn) {
      state.isLoggedIn = isLoggedIn
    },
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
    },
    CLEAR_USER_STATE(state) {
      state.isLoggedIn = false
      state.userInfo = null
    }
  },
  actions: {
    // 初始化用户状态
    initUserState({ commit }) {
      const token = getToken()
      const userInfo = getUserInfo()
      
      if (token && userInfo) {
        commit('SET_LOGIN_STATE', true)
        commit('SET_USER_INFO', userInfo)
      } else {
        commit('SET_LOGIN_STATE', false)
        commit('SET_USER_INFO', null)
      }
    },
    // 登录
    login({ commit }, userData) {
      commit('SET_LOGIN_STATE', true)
      commit('SET_USER_INFO', userData)
    },
    // 登出
    logout({ commit }) {
      clearAuth()
      commit('CLEAR_USER_STATE')
    }
  },
  modules: {
  }
})
